<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" inline v-show="showSearch">
          <el-form-item label="题干名称" prop="content">
            <el-input
              v-model="queryParams.content"
              placeholder="请输入题干名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="学科名称" prop="subjectId">
            <el-select
              v-model="queryParams.subjectId"
              placeholder="请选择"
              @change="subChange"
            >
              <el-option
                v-for="item in subjectOptions"
                :key="item.id"
                :label="item.subject"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="知识点名称" prop="knowledgeId">
            <el-select
              v-model="queryParams.knowledgeId"
              placeholder="请选择"
              @change="handleQuery"
            >
              <el-option
                v-for="item in knowledgeOptions"
                :key="item.id"
                :label="item.knowledge"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="table-tools mb8">
          <div>
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
            <!-- <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改</el-button
            > -->
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              >导出</el-button
            >
          </div>
          <div>
            <right-toolbar
              v-model:showSearch="showSearch"
              @queryTable="getList"
            />
          </div>
        </div>

        <el-table
          v-loading="loading"
          :data="questionList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" prop="id" width="50" align="center" />
          <el-table-column
            label="题型"
            width="100"
            align="center"
            key="topicName"
            prop="topicName"
          />
          <el-table-column
            label="所属学科"
            align="center"
            key="subName"
            prop="subName"
            width="200"
            show-overflow-tooltip
          />

          <el-table-column
            label="题干名称"
            align="center"
            key="questr"
            prop="questr"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span v-html="scope.row.questr"></span>
            </template>
          </el-table-column>
          <el-table-column
            label="分数"
            align="center"
            key="score"
            prop="score"
            width="50"
          />
          <el-table-column
            label="难度"
            align="center"
            key="difficult"
            prop="difficult"
            width="150"
          >
            <template #default="scope">
              <el-rate disabled v-model="scope.row.difficult"></el-rate>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="创建时间"
            align="center"
            prop="creatTime"
            width="160"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.creatTime) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="300"
          >
            <template #default="scope">
              <el-button
                type="primary"
                link
                icon="Edit"
                @click="handlePreview(scope.row)"
                >预览
              </el-button>
              <el-button
                type="primary"
                link
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                type="primary"
                link
                icon="Delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改题库对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        :model="form"
        :rules="rules"
        ref="knowledgeRef"
        label-width="120px"
      >
        <el-row style="max-height: 700px; overflow: auto">
          <el-col :span="24">
            <el-form-item label="学科名称" prop="subjectId">
              <el-select
                v-model="form.subjectId"
                placeholder="请选择"
                style="width: 100%"
                @change="subjectChange"
              >
                <el-option
                  v-for="item in subjectOptions"
                  :key="item.id"
                  :label="item.subject"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题目类型" prop="topicId">
              <el-radio-group
                v-model="form.topicId"
                @change="questionTypeChange"
                :disabled="title == '修改试题'"
              >
                <el-radio-button
                  v-for="item in topicTypeList"
                  :key="item.id"
                  :label="item.id"
                  >{{ item.label }}</el-radio-button
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题干名称" prop="content">
              <el-button type="plain" icon="edit" @click="handleEditQuestion"
                >编辑</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="">
              <div v-html="form.content" style="width: 100%"></div>
            </el-form-item>
          </el-col>
          <template v-if="form.topicId == '1' || form.topicId == '2'">
            <el-col :span="24">
              <el-form-item label="选项" prop="items">
                <template v-for="item in form.items" :key="item.pre">
                  <el-input
                    placeholder="请输入内容"
                    v-model="item.content"
                    style="margin-bottom: 10px"
                  >
                    <template #prepend>{{ item.pre }}</template>
                  </el-input>
                </template>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="24">
            <el-form-item label="标答" prop="correct">
              <template v-if="form.topicId == '1' || form.topicId == '3'">
                <el-radio-group v-model="form.correct">
                  <el-radio
                    :label="item.pre"
                    v-for="item in form.items"
                    :key="item.pre"
                    >{{ item.pre }}</el-radio
                  >
                </el-radio-group>
              </template>
              <template v-if="form.topicId == '2'">
                <el-checkbox-group v-model="multipleCheck">
                  <el-checkbox
                    :label="item.pre"
                    v-for="item in form.items"
                    :key="item.pre"
                    >{{ item.pre }}</el-checkbox
                  >
                </el-checkbox-group>
              </template>
              <template v-if="form.topicId == '6' || form.topicId == '7'">
                <el-input
                  type="textarea"
                  placeholder="请输入内容"
                  v-model="form.correct"
                  maxlength="100"
                  show-word-limit
                >
                </el-input>
              </template>
              <template v-if="form.topicId == '5'">
                <template v-for="item in form.items" :key="item.pre">
                  <el-input
                    placeholder="请输入内容"
                    v-model="item.content"
                    style="margin-bottom: 10px"
                  >
                    <template #prepend>{{ item.pre }}</template>
                  </el-input>
                </template>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="解析" prop="analyzes">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="form.analyzes"
                maxlength="100"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分数" prop="score">
              <el-input-number
                :disabled="title == '修改试题'"
                v-model="form.score"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="难度" prop="difficult">
              <el-rate
                v-model="form.difficult"
                @change="difficultChange"
              ></el-rate>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="知识点" prop="knowledgeId">
              <el-select
                v-model="form.knowledgeId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in knowledgeOptions"
                  :key="item.id"
                  :label="item.knowledge"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑题目数据 -->
    <el-dialog
      title="编辑题干"
      v-model="editorOpen"
      v-if="editorOpen"
      width="600px"
      append-to-body
    >
      <Editor @change="editorChange" :propValue="form.content" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="editorConfirm">确 定</el-button>
          <el-button @click="editorCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="预览"
      v-model="questionPreview"
      v-if="questionPreview"
      width="600px"
      append-to-body
    >
      <el-row :gutter="16" justify="space-between">
        <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
          <span v-html="currentRow.content"></span>
        </el-col>
      </el-row>
      <template v-if="currentRow.topicId == 1 || currentRow.topicId == 2">
        <el-row :gutter="16" justify="space-between" style="margin-top: 16px">
          <el-col
            :xl="6"
            :lg="6"
            :md="6"
            :sm="24"
            :xs="24"
            v-for="item in currentRow.items"
            :key="item.pre"
          >
            <span style="margin-right: 10px">{{ item.pre }}:</span>
            <span>{{ item.content }}</span>
          </el-col>
        </el-row>
      </template>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="questionPreview = false"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import { getSubjectList } from "@/api/core/subject";
import { getTopicList } from "@/api/core/topic";
import {
  getQuestionList,
  addQuestion,
  editQuestion,
  deleteQuestionByIds,
} from "@/api/core/question";
import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
} from "vue";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const topicTypeList = ref([
  { id: 1, label: "单选" },
  { id: 2, label: "多选" },
  { id: 3, label: "判断" },
  { id: 5, label: "填空" },
  { id: 6, label: "简答" },
  { id: 7, label: "编程题" },
]);
const questionList = ref([]);
const knowledgeOptions = ref([]);
const subjectOptions = ref([]);
const open = ref(false);
const editorOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// const dateRange = ref([]);
const editorHtml = ref("");
const multipleCheck = ref([]);
const questionPreview = ref(false);
const currentRow = ref({});
const userStore = useUserStore();
// 校验标准答案
const validateCorrent = (rule, value, callback) => {
  if (
    form.value.topicId == 1 ||
    form.value.topicId == 3 ||
    form.value.topicId == 6 ||
    form.value.topicId == 7
  ) {
    if (value.length > 0) {
      callback();
    } else {
      callback(new Error("标准答案不能为空"));
    }
  }
  if (form.value.topicId == 2) {
    if (multipleCheck.value.length > 0) {
      callback();
    } else {
      callback(new Error("标准答案不能为空"));
    }
  }
  // 填空
  if (form.value.topicId == 5) {
    if (form.value.items.every((it) => it.content)) {
      callback();
    } else {
      callback(new Error("标准答案不能为空"));
    }
  }
};
const validateItems = (rule, value, callback) => {
  if (form.value.topicId == 1 || form.value.topicId == 2) {
    if (value.every((it) => it.content)) {
      callback();
    } else {
      callback(new Error("选项不能为空"));
    }
  }
};
const validateScore = (rule, value, callback) => {
  if (value > 0) {
    callback();
  } else {
    callback(new Error("分数最少为1分"));
  }
};
const validateDifficult = (rule, value, callback) => {
  console.log("检验难度", value);
  if (value > 0) {
    callback();
  } else {
    callback(new Error("请选择难度"));
  }
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    knowledge: undefined,
    subjectId: undefined,
    content: undefined,
  },

  rules: {
    knowledgeId: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "知识点名称不能为空",
      },
    ],
    subjectId: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "学科不能为空",
      },
    ],
    content: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "题目不能为空",
      },
    ],
    items: [
      {
        required: true,
        trigger: "blur",
        message: "选项不能为空",
        validator: validateItems,
      },
    ],
    correct: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "标答不能为空",
        validator: validateCorrent,
      },
    ],
    analyzes: [
      {
        required: true,
        trigger: "blur",
        message: "解析不能为空",
      },
    ],
    difficult: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: validateDifficult,
      },
    ],
    score: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: validateScore,
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

/** 查询题目列表 */
function getList() {
  loading.value = true;
  // proxy.addDateRange(queryParams.value, dateRange.value)
  getQuestionList(queryParams.value).then((res) => {
    loading.value = false;
    questionList.value = res.rows.map((item) => {
      return {
        ...item,
        questr: checkEmpty(item.content),
      };
    });
    total.value = res.total;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const classIds = row.id || ids.value.toString();
  proxy.$modal
    .confirm("是否确定删除该题目？")
    .then(function () {
      return deleteQuestionByIds(classIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置操作表单 */
function reset() {
  form.value = {
    id: null,
    subjectId: "",
    knowledgeId: "",
    topicId: 1,
    content: "",
    items: [
      { pre: "A", content: "" },
      { pre: "B", content: "" },
      { pre: "C", content: "" },
      { pre: "D", content: "" },
    ],
    correct: "",
    analyzes: "",
    difficult: "",
    score: "",
  };
  multipleCheck.value = [];
  knowledgeOptions.value = [];
  proxy.resetForm("knowledgeRef");
}
function questionTypeChange(val) {
  console.log("选项变化", val);
  // 选项改变重置值
  form.value.knowledgeId = "";
  form.value.content = "";
  form.value.items = "";
  form.value.correct = "";
  form.value.analyzes = "";
  form.value.difficult = "";
  form.value.score = "";
  // 单选和多选配置；默认选项
  if (val == 1 || val == 2) {
    form.value.items = [
      { pre: "A", content: "" },
      { pre: "B", content: "" },
      { pre: "C", content: "" },
      { pre: "D", content: "" },
    ];
    if (val == 2) {
      form.value.correct = [];
    }
  } else if (val == 3) {
    // 判断题配置对错选项
    form.value.items = [
      { pre: "对", content: "" },
      { pre: "错", content: "" },
    ];
  } else if (val == 6 || val == 7) {
    form.value.items = [];
  } else if (val == 5) {
    form.value.items = [];
  }
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加试题";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value.id = row.id;
  // 学科赋值
  form.value.subjectId = row.subjectId;
  // 知识点赋值
  subjectChange(row.subjectId);
  form.value.knowledgeId = row.knowledgeId;
  // 题型赋值
  form.value.topicId = row.topicId;
  // 题干赋值
  form.value.content = row.content;
  // 选项赋值
  form.value.items = JSON.parse(row.items);
  // 标准答案赋值
  form.value.correct = row.correct;
  // 解析赋值
  form.value.analyzes = row.analyzes;
  // 难度赋值
  form.value.difficult = row.difficult;
  // 分数赋值
  form.value.score = row.score;
  open.value = true;
  title.value = "修改试题";
  if (form.value.topicId == 2) {
    multipleCheck.value = form.value.correct.split(",");
  }
}
function handlePreview(row) {
  console.log("打印row", row);
  let proRow = JSON.parse(JSON.stringify(row));
  currentRow.value = proRow;
  currentRow.value.items = JSON.parse(proRow.items);
  console.log("打印row", currentRow.value);
  questionPreview.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["knowledgeRef"].validate((valid) => {
    if (valid) {
      // 多选标准答案数组的处理
      if (form.value.topicId == 2) {
        form.value.correct = multipleCheck.value.toString();
      } else if (form.value.topicId == 5) {
        // 填空题增加标准答案
        form.value.correct = JSON.stringify(form.value.items);
      }
      let param = JSON.parse(JSON.stringify(form.value));
      param.items = JSON.stringify(form.value.items);
      if (form.value.id) {
        editQuestion(param).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addQuestion(param).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 编辑题干
function handleEditQuestion() {
  editorOpen.value = true;
}
// 学科改变
function subjectChange(val) {
  form.value.knowledgeId = "";
  getTopicList({ subId: val }).then((res) => {
    knowledgeOptions.value = res.rows;
  });
}
// 主页面得学科搜索
function subChange(val) {
  queryParams.value.knowledgeId = "";
  getTopicList({ subId: val }).then((res) => {
    knowledgeOptions.value = res.rows;
  });
  queryParams.value.pageNum = 1;
  getList();
}
//编辑完题干，确认事件
function editorConfirm() {
  // 去掉p标签

  if (form.value.topicId == 5) {
    let len = countOccurrences(editorHtml.value, "<u>");
    if (len > 0) {
      let newArr = new Array(len).fill(0);
      form.value.items = newArr.map((item, index) => {
        return {
          pre: index + 1,
          content: "",
        };
      });
    } else {
      proxy.$modal.msgWarning("请添加下划线为填空");
      return;
    }
  }
  console.log("editorHtml.value", editorHtml.value);
  // let saveContent = checkEmpty(editorHtml.value);
  form.value.content = editorHtml.value.replace(/<p><br><\/p>/g, "");
  // return;
  // if (saveContent.length > 0) {
  //   form.value.content = editorHtml.value;
  //   // form.value.content =
  //   //   '<pre><code style="word-wrap: normal;font-family: Consolas, Monaco, Andale Mono, Ubuntu Mono, monospace;-webkit-hyphens: none;hyphens: none;line-height: 1.5;margin: 0.5em 0;overflow: auto;padding: 1em;-moz-tab-size: 4;-o-tab-size: 4;tab-size: 4;text-align: left;text-shadow: 0 1px #fff;white-space: pre;word-break: normal;word-spacing: normal;background-color: #f5f2f0;border: 1px solid #e8e8e8;border-radius: 4px 4px;display: block;font-size: 14px;padding: 10px;text-indent: 0;" class="language-python">import pandas as pdimport numpy as np#请继续补充</code></pre>';

  //   proxy.$refs["knowledgeRef"].clearValidate("content");
  // }
  console.log("dsfsdffadsfdsfa", form.value.content);
  editorOpen.value = false;
}
// 去除p标签
function checkEmpty(str) {
  let res = str.replace(/<p>/g, "");
  res = res.replace(/<\/p>/g, "");
  res = res.replace(/<br>/g, "");
  res = str.replace(/<img[^>]*>/g, "");
  res = res.replace(/<pre>.+?<\/pre>/gis, "");
  return res.trim();
}

// 计算特殊字符串出现的次数
function countOccurrences(str, charToCount) {
  // 使用正则表达式，`g`标志用于全局搜索
  const regex = new RegExp(charToCount, "g");
  // 使用`match`方法计算匹配到的个数
  return (str.match(regex) || []).length;
}
function editorCancel() {
  editorOpen.value = false;
}
function editorChange(htm) {
  console.log("打印", htm);
  editorHtml.value = htm;
}
function difficultChange() {
  proxy.$refs["knowledgeRef"].clearValidate("difficult");
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download("/core/minio", {}, `config_${new Date().getTime()}.xlsx`);
}
// 首次请求学科列表
getSubjectList().then((res) => {
  subjectOptions.value = res.rows;
  getList();
});
</script>

<style lang="scss">
// 代码样式
code {
  word-wrap: normal;
  font-family: Consolas, Monaco, Andale Mono, Ubuntu Mono, monospace;
  -webkit-hyphens: none;
  hyphens: none;
  line-height: 1.5;
  margin: 0.5em 0;
  overflow: auto;
  padding: 1em;
  -moz-tab-size: 4;
  -o-tab-size: 4;
  tab-size: 4;
  text-align: left;
  text-shadow: 0 1px #fff;
  white-space: pre;
  word-break: normal;
  word-spacing: normal;
  background-color: #f5f2f0;
  border: 1px solid #e8e8e8;
  border-radius: 4px 4px;
  display: block;
  font-size: 14px;
  padding: 10px;
  text-indent: 0;
}
</style>
